<?php

/**
 * User Controller.
 *
 * Helpful methods to make Controller.
 *
 * PHP versions 5
 * CAKEPHP versions 2.x
 * 
 * Green CMS - Content Management System and Framework Powerfull by Cakephp
 * Copyright 2012, GREEN GLOBAL CO., LTD (toancauxanh.vn)
 * 
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2011, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @author        Technology Lab No.I <tech1@toancauxanh.vn>
 * @link          
 * @package       User.Controller
 * @since         Green v 1.0
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('UserAppController', 'User.Controller');

/**
 * Autocomple in PHP's IDE solution
 * 
 * @property User $User
 * 
 */
Class UserController extends UserAppController {

    /**
     * Use model class
     *
     * @var array
     */
    public $uses = array('User.User');

    /**
     * Called after the controller action.  
     *
     * @return void
     */
    public function beforeRender() {
        parent::beforeRender();
        if (in_array($this->request['action'], array('admin_add', 'admin_edit'))) {
            $layouts = $this->Dashboard->get($this->User, 'layouts');
            if (empty($layouts)) {
                $layouts = array(null, array_keys($this->User->schema()));
            }
            $this->set('_layouts', $layouts);
        }
    }

    function login() {

        $this->layout = 'login';
        $antiDetector = null;

//        $Captcha = $this->Components->load('Tvpanel.Captcha');
//        if (!empty($this->request->data['captcha']) && $Captcha->verry($this->request->data['captcha'])) {
//            $antiDetector = false;
//        }

        if ($this->Auth->login(array(), $antiDetector)) {
            $user= $this->Auth->user();
            $this->Session->write('user', $user);
            $this->log('The user are logged into the system', LOG_LOGIN);
            //save session user
            return $this->redirect($this->Auth->redirect());
        } else {
            if ($this->request->is('post')) {
                if (!$this->Auth->isDetector()) {
                    $this->setFlash(__d('system', 'Username or password is incorrect'));
                } 
            }
        }
        
        $this->set('user', $this->Auth->user());
    }

    function logout() {
        $this->log('The user has been logout of system', LOG_LOGIN);
        $this->redirect($this->Auth->logout());
    }

    function admin_login() {
        $this->login();
    }

    function admin_logout() {
        $this->logout();
    }

    /**
     * Admin user
     *
     * @return void
     */
    public function admin_index() {
        if ($this->request->is('post')) {
            $data = array_merge(array('task' => '', 'id' => array(0)), $this->request->data['Paginate']);
            switch (strtolower($data['task'])) {
                case 'save': {
                        $this->Dashboard->redirect(array('controller' => 'permissions', 'ext' => false));
                    }
                case 'add': {
                        $this->Dashboard->redirect(array('action' => 'add', $data['id'][0]));
                    }
                case 'edit': {
                        $this->Dashboard->redirect(array('action' => 'edit', $data['id'][0]));
                    }
                case 'remove': {
                        $this->Dashboard->redirect(array('action' => 'delete', '?' => array('keys' => $data['id'])));
                    }
            }
        }
        $_paginate = array(
            'order' => array('rght' => 'asc'),
            'fields' => array('id'),
            'conditions' => array()
        );
        $this->Dashboard->parseRequest($this->User, $_paginate, array('fullname'));
        $users = $this->paginate();

        $roleMap = $this->User->roleMap();
        $roles = $this->User->Role->find('list', array('conditions' => array(
                'not' => array('id' => array($roleMap['authenticated'], $roleMap['anonymous'])))));

        $this->Dashboard->translateMaps($this->User, $users);
        $this->Dashboard->toolbar(__d('system', 'Users management'), array(
            'save' => array('action' => 'add', 'text' => __d('system', 'Permissions')),
            'add' => array('action' => 'add', 'text' => __d('system', 'Add')),
            'edit' => array('action' => 'edit', 'text' => __d('system', 'Edit')),
            'remove' => array('action' => 'removes', 'text' => __d('system', 'Delete'))
        ));
        $this->set(compact('roles', 'users'));
    }

    /**
     * Add data
     *
     * @return void
     */
    public function admin_add($id = null, $parent = null) {
        $this->Dashboard->exists($this->User, $id, false);
        $this->Dashboard->toolbar(__d('system', 'Add new User'), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'next' => array('action' => 'save', 'text' => __d('system', 'Save & Add New')),
            'cancel' => __d('system', 'Cancel')
        ));
        if ($this->request->is('post')) {
            $this->User->create();
            $task = strtolower($this->request->data['Paginate']['task']);
            if (empty($task) || $task === 'cancel') {
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            }
            if ($this->User->save($this->request->data)) {
                $this->setFlash(__d('system', 'The %s has been saved', __d('system', 'User')), 'success');
                switch ($task) {
                    case 'next': {
                            $this->redirect($this->request->here(false));
                        }
                    case 'apply': {
                            $this->Dashboard->redirect(array('action' => 'edit', $this->User->getInsertID()), false, true);
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be saved. Please, try again.', __d('system', 'User')), 'error');
            }
        } elseif ($id) {
            $this->request->data = $this->User->read(array('contain' => array('Role' => array('fields' => 'id'))), $id);
            $this->request->data['User']['Role'] = Set::combine($this->request->data, 'Role.{n}.id', 'Role.{n}.id');
        
        }

        $roleMap = $this->User->roleMap();
        $roles = $this->User->Role->find('list', array('conditions' => array(
                'not' => array('id' => $roleMap['anonymous']))));
        if (isset($roles[$roleMap['authenticated']])) {
            $roles[$roleMap['authenticated']] = array(
                'name' => $roles[$roleMap['authenticated']],
                'value' => $roleMap['authenticated'],
                'disabled' => true,
                'checked' => true,
            );
        }
        $this->set(compact('roles', 'id'));
    }

    /**
     * Edit data
     *
     * @return void
     */
    public function admin_edit($id = null) {
        $this->Dashboard->exists($this->User, $id);
        $this->Dashboard->toolbar(__d('system', 'Edit User #%s', $id), array(
            'save' => array('action' => 'save', 'text' => __d('system', 'Save')),
            'remove' => array('action' => 'remove', 'text' => __d('system', 'Delete')),
            'cancel' => __d('system', 'Cancel')
        ));
        if ($this->request->is('post')) {
            
            $task = strtolower($this->request->data['Paginate']['task']);
            switch ($task) {
                case 'remove': {
                        $this->Dashboard->redirect(array('action' => 'delete', '?' => array('keys' => $id)), false, true);
                    }
                case 'cancel': {
                        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
                    }
            }
            if ($this->User->save($this->request->data)) {
                $this->setFlash(__d('system', 'The %s has been updated', __d('system', 'User')), 'success');
                switch ($task) {
                    case 'apply': {
                            $this->redirect($this->request->here(false));
                        }
                }
                $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
            } else {
                $this->setFlash(__d('system', 'The %s could not be updated. Please, try again.', __d('system', 'User')));
            }
        } else {
            $this->request->data = $this->User->read(array('contain' => array('Role' => array('fields' => 'id'))), $id);
            $this->request->data['User']['Role'] = Set::combine($this->request->data, 'Role.{n}.id', 'Role.{n}.id');
        }

        $roleMap = $this->User->roleMap();
        $roles = $this->User->Role->find('list', array('conditions' => array(
                'not' => array('id' => $roleMap['anonymous']))));
        if (isset($roles[$roleMap['authenticated']])) {
            $roles[$roleMap['authenticated']] = array(
                'name' => $roles[$roleMap['authenticated']],
                'value' => $roleMap['authenticated'],
                'disabled' => true,
                'checked' => true,
            );
        }
        $this->set(compact('roles', 'id'));
    }

    /**
     * Delete data
     *
     * @return void
     */
    public function admin_delete() {
        if (empty($this->request->query['keys'])) {
            $this->setFlash(__d('system', 'Select elements should be deleted from the list below!', __d('system', 'User')));
        } else {
            $complete = 0;
            $message = null;
            $keys = (array) $this->request->query['keys'];
            foreach ($keys as $key) {
                if (!$this->User->delete($key)) {
                    $message = $this->User->getMessage();
                    if (!$message) {
                        $message = __d('system', 'Cannot delete row #%s.', $key);
                    }
                    break;
                } else {
                    $complete++;
                }
            }
            if ($message) {
                $message = __d('system', '<br/>The processing has stopped because : <b>%s</b>', $message);
            }
            $this->setFlash(__d('system', 'The %1$s has been deleted %2$s / %3$s rows.', __d('system', 'User'), $complete, count($keys)) . $message, 'warning');
        }
        $this->Dashboard->redirect(array('action' => 'index', 'ext' => false), true);
    }

}

?>
